<%@ page contentType="text/html;charset=UTF-8" %>
<%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core" %>
<%@ taglib prefix="fn" uri="http://java.sun.com/jsp/jstl/functions" %>
<html>
<head>
    <%@ include file="include/header.jsp" %>
    <script src="${pageContext.request.contextPath}/js/admin/admin_home.js"></script>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/admin/admin_home.css"/>
    <link rel="stylesheet" href="${pageContext.request.contextPath}/css/admin/admin_main.css"/>
    <script>
        $(function () {
            if ($("#product_id").val() !== "") {
                //设置产品种类值
                $('#select_product_category').selectpicker('val', '${product.productCategoryId}');
                //设置产品状态
                var product_isEnabled = '${product.productIsEnabled}';
                $("input[name='productIsEnabled']").each(function () {
                    if ($(this).val() === product_isEnabled) {
                        $(this).prop("checked", true);
                        if ($(this).val() === "1") {
                            $("#text_productState_details_msg").text("提示：产品停售时无法进行交易").attr("title", "提示：产品停售时无法进行交易").css("left", 0).css("opacity", "1");
                        }
                        return false;
                    }
                });
                //设置产品编号
                $("#span_product_id").text('${product.productId}');
                //设置产品创建日期
                $("#span_product_create_date").text('${product.productCreateDate}');
                //判断文件是否允许上传
                checkFileUpload($("#product_single_list"), 5);
                checkFileUpload($("#product_details_list"), 8);
            }
            //产品分类改变时
            $("#select_product_category").change(function () {
                //如果产品分类没有选择
                if ($(this).val() == -1) {
                    var listDiv = $(".details_property_list");
                    listDiv.empty().append("<span class='details_title text_info'>属性值信息</span>");
                    return;
                }
                $.ajax({
                    url: "/admin/property/" + $(this).val(),
                    type: "get",
                    data: null,
                    success: function (data) {
                        $(".loader").css("display", "none");
                        //清空原有数据
                        var listDiv = $(".details_property_list");
                        listDiv.empty().append("<span class='details_title text_info'>属性值信息</span>");
                        //显示产品属性数据
                        if (data.propertyList.length > 0) {
                            for (var i = 0; i < data.propertyList.length; i++) {
                                var propertyId = data.propertyList[i].propertyId;
                                var propertyName = data.propertyList[i].propertyName;
                                if (data.propertyList[i + 1] !== undefined) {
                                    var nextPropertyId = data.propertyList[i + 1].propertyId;
                                    var nextPropertyName = data.propertyList[i + 1].propertyName;
                                    i++;
                                    listDiv.append("<label class='frm_label lbl_property_name text_info' id='lbl_product_property_" + propertyId + "' for='input_product_property_" + propertyId + "'>" + propertyName + "</label><input class='frm_input' id='input_product_property_" + propertyId + "' type='text' maxlength='50' name='propertys[" + propertyId + "]'/><label class='frm_label lbl_property_name text_info' id='lbl_product_property_" + nextPropertyId + "' for='input_product_property_" + nextPropertyId + "'>" + nextPropertyName + "</label><input class='frm_input' id='input_product_property_" + nextPropertyId + "' type='text' maxlength='50' name='propertys[" + nextPropertyId + "]'/><div class='br'></div>");
                                } else {
                                    listDiv.append("<label class='frm_label lbl_property_name text_info' id='lbl_product_property_" + propertyId + "' for='input_product_property_" + propertyId + "'>" + propertyName + "</label><input class='frm_input' id='input_product_property_" + propertyId + "' type='text' maxlength='50' name='propertys[" + propertyId + "]'/><div class='br'></div>");
                                }
                            }
                        }
                    }
                })
            });

            //单击图片列表项时
            $(".details_picList").on("click", "li:not(.details_picList_fileUpload)", function () {
                var img = $(this);
                var productImage_id = img.children("img").attr("name");
                var fileUploadInput = $(this).parents("ul").children(".details_picList_fileUpload");

                $("#btn-ok").unbind("click").click(function () {
                    img.remove();
                    fileUploadInput.css("display", "inline-block");
                    $('#modalDiv').modal("hide");
                });

                $(".modal-body").text("您确定要删除该产品图片吗？");
                $('#modalDiv').modal();
            });
            //改变产品状态时
            $('input:radio').click(function () {
                if ($(this).val() === "1") {
                    styleUtil.errorShow($("#text_productState_details_msg"), "提示：产品停售时无法进行交易");
                } else {
                    styleUtil.errorHide($("#text_productState_details_msg"));
                }
            });

            //获取到输入框焦点时
            $("input:text").focus(function () {
                styleUtil.basicErrorHide($(this).prev("label"));
            });

            //点击保存按钮提交表单时
            $("#editForm").submit(function () {
                var product_category_id = $("#select_product_category").selectpicker("val");
                var product_isEnabled = $("input[name='productIsEnabled']:checked").val();
                var product_name = $.trim($("#input_product_name").val());
                var product_title = $.trim($("#input_product_title").val());
                var product_price = $.trim($("#input_product_price").val());
                var product_sale_price = $.trim($("#input_product_sale_price").val());

                //校验数据合法性
                var yn = true;
                if (product_category_id === "-1") {
                    styleUtil.errorShow($("#text_productState_details_msg"), "请选择产品分类！");
                    yn = false
                }
                if (product_isEnabled === undefined) {
                    styleUtil.errorShow($("#text_productState_details_msg"), "请选择产品状态！");
                    yn = false;
                }
                if (product_name === "") {
                    styleUtil.basicErrorShow($("#lbl_product_name"));
                    yn = false;
                }
                if (product_title === "") {
                    styleUtil.basicErrorShow($("#lbl_product_title"));
                    yn = false;
                }
                if (product_price === "" || isNaN(product_price)) {
                    styleUtil.basicErrorShow($("#lbl_product_price"));
                    yn = false;
                }
                if (product_sale_price === "" || isNaN(product_sale_price)) {
                    styleUtil.basicErrorShow($("#lbl_product_sale_price"));
                    yn = false;
                }
                return yn;
            })
        });

        //图片上传
        function uploadImage(fileDom) {
            //获取文件
            var file = fileDom.files[0];
            //判断类型
            var imageType = /^image\//;
            if (file === undefined || !imageType.test(file.type)) {
                $("#btn-ok").unbind("click").click(function () {
                    $("#modalDiv").modal("hide");
                });
                $(".modal-body").text("请选择图片！");
                $('#modalDiv').modal();
                return;
            }
            //判断大小
            if (file.size > 512000000) {
                $("#btn-ok").unbind("click").click(function () {
                    $("#modalDiv").modal("hide");
                });
                $(".modal-body").text("图片大小不能超过500K！");
                $('#modalDiv').modal();
                return;
            }
            var ul = $(fileDom).parents(".details_picList");
            var type;
            if (ul.attr("id") === "product_single_list") {
                type = "single";
            } else {
                type = "details";
            }
            //清空值
            $(fileDom).val('');
            var formData = new FormData();
            formData.append("file", file);
            formData.append("imageType", type);
            //上传图片
            $.ajax({
                url: "/admin/product/uploadProductImage",
                type: "post",
                data: formData,
                contentType: false,
                processData: false,
                dataType: "json",
                mimeType: "multipart/form-data",
                success: function (data) {
                    $(fileDom).attr("disabled", false).prev("span").text("上传图片");
                    if (data.success) {
                        if (type === "single") {
                            $(fileDom).parent('.details_picList_fileUpload').before(
                                "<li><img src='" + data.url + "' width='128px' height='128px' name='new'/><input type='hidden' name='singlePicture' value='" + data.url + "'></li>");
                            checkFileUpload(ul, 5);
                        } else {
                            $(fileDom).parent('.details_picList_fileUpload').before("" +
                                "<li><img src='" + data.url + "' width='128px' height='128px' name='new'/><input type='hidden' name='detailsPicture' value='" + data.url + "'></li>");
                            checkFileUpload(ul, 8);
                        }
                    } else {
                        alert("图片上传异常！");
                    }
                },
                beforeSend: function () {
                    $(fileDom).attr("disabled", true).prev("span").text("图片上传中...");
                },
                error: function () {

                }
            });
        }

        //判断是否允许上传文件
        function checkFileUpload(obj, size) {
            if (obj.children("li:not(.details_picList_fileUpload,:hidden)").length >= size) {
                obj.children(".details_picList_fileUpload").css("display", "none");
            } else {
                obj.children(".details_picList_fileUpload").css("display", "inline-block");
            }
        }
    </script>
    <style rel="stylesheet">
        .bootstrap-select:not([class*=col-]):not([class*=form-control]):not(.input-group-btn) {
            margin: 0 130px 0 0;
        }

        .frm_input {
            margin-right: 130px;
        }

        .frm_error_msg {
            white-space: nowrap;
        }

        .warn_height {
            max-height: 25px;
        }

        div.br {
            height: 20px;
        }

        .details_property_list label {
            margin-left: 10px;
        }
    </style>
</head>
<body>
<%@include file="include/menuPage.jsp" %>
<!--菜单回显-->
<c:set var="currentMenu" value="product"/>
<form action="/admin/product/saveOrUpdate" method="post" id="editForm">
    <div class="details_div_first">

        <div class="frm_div_last warn_height">
            <label class="frm_label text_info" id="lbl_product_category_id" for="select_product_category">产品类型</label>
            <select class="selectpicker" id="select_product_category" data-size="8" name="productCategoryId">
                <option value="-1">选择产品类型</option>
                <c:forEach items="${categoryList}" var="category">
                    <option value="${category.categoryId}">${category.categoryName}</option>
                </c:forEach>
            </select>

            <label class="frm_label text_info" id="lbl_product_isEnabled"
                   for="radio_product_isEnabled_true">产品状态</label>
            <input id="radio_product_isEnabled_true" name="productIsEnabled" type="radio" value="0" checked>
            <label class="frm_label text_info" id="lbl_product_isEnabled_true"
                   for="radio_product_isEnabled_true">销售中</label>
            <input id="radio_product_isEnabled_false" name="productIsEnabled" type="radio" value="1">
            <label class="frm_label text_info" id="lbl_product_isEnabled_false"
                   for="radio_product_isEnabled_false">停售中</label>
            <span class="frm_error_msg" id="text_productState_details_msg"></span>
        </div>
    </div>
    <div class="details_div">
        <span class="details_title text_info">基本信息</span>
        <div class="frm_div">
            <label class="frm_label text_info" id="lbl_product_id">产品编号</label>
            <span class="details_value" id="span_product_id">系统指定</span>
            <input type="hidden" value="${product.productId}" id="product_id" name="productId"/>
            <label class="frm_label text_info" id="lbl_product_create_date">上架日期</label>
            <span class="details_value" id="span_product_create_date">系统指定</span>
            <input type="hidden" name="productCreateDate" value="${product.productCreateDate}">
        </div>
        <div class="frm_div">
            <label class="frm_label text_info" id="lbl_product_name" for="input_product_name">产品名称</label>
            <input class="frm_input" id="input_product_name" type="text" maxlength="50" name="productName"
                   value="${product.productName}"/>
            <label class="frm_label text_info" id="lbl_product_title" for="input_product_title">产品标题</label>
            <input class="frm_input" id="input_product_title" type="text" maxlength="50" name="productTitle"
                   value="${product.productTitle}"/>
        </div>
        <div class="frm_div_last">
            <label class="frm_label text_info" id="lbl_product_price" for="input_product_price">产品原价</label>
            <input class="frm_input details_unit" id="input_product_price" type="text" maxlength="10"
                   name="productPrice" value="${product.productPrice}"/>
            <span class="details_unit text_info">元</span>
            <label class="frm_label text_info" id="lbl_product_sale_price" for="input_product_sale_price">产品促销价</label>
            <input class="frm_input details_unit" id="input_product_sale_price" type="text" maxlength="10"
                   name="productSalePrice" value="${product.productSalePrice}"/>
            <span class="details_unit text_info">元</span>
        </div>
    </div>
    <div class="details_div">
        <span class="details_title text_info">概述图片</span>
        <ul class="details_picList" id="product_single_list">
            <c:forEach items="${product.productSinglePicList}" var="image">
                <li><img
                        src="${image.productimageSrc}"
                        id="pic_single_${image.productimageId}" width="128px" height="128px"
                        name="${image.productimageId}"/>
                    <input type="hidden" name="singlePicture" id="${image.productimageSrc}"
                           value="${image.productimageSrc}"/>
                </li>
            </c:forEach>
            <li class="details_picList_fileUpload">
                <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1528"
                     width="40" height="40">
                    <path d="M0 512C0 229.230208 229.805588 0 512 0 794.769792 0 1024 229.805588 1024 512 1024 794.769792 794.194412 1024 512 1024 229.230208 1024 0 794.194412 0 512Z"
                          p-id="1529" fill="#FF7874"></path>
                    <path d="M753.301333 490.666667l-219.946667 0L533.354667 270.741333c0-11.776-9.557333-21.333333-21.354667-21.333333-11.776 0-21.333333 9.536-21.333333 21.333333L490.666667 490.666667 270.72 490.666667c-11.776 0-21.333333 9.557333-21.333333 21.333333 0 11.797333 9.557333 21.354667 21.333333 21.354667L490.666667 533.354667l0 219.904c0 11.861333 9.536 21.376 21.333333 21.376 11.797333 0 21.354667-9.578667 21.354667-21.333333l0-219.946667 219.946667 0c11.754667 0 21.333333-9.557333 21.333333-21.354667C774.634667 500.224 765.077333 490.666667 753.301333 490.666667z"
                          p-id="1530" fill="#FFFFFF"></path>
                </svg>
                <span>点击上传</span>
                <input type="file" onchange="uploadImage(this)" accept="image/*">
            </li>
        </ul>
    </div>
    <div class="details_div">
        <span class="details_title text_info">详情图片</span>
        <ul class="details_picList" id="product_details_list">
            <c:forEach items="${product.productDetailsPicList}" var="image">
                <li>
                    <img
                            src="${image.productimageSrc}"
                            id="pic_details_${image.productimageId}" width="128px" height="128px"
                            name="${image.productimageId}"/>
                    <input type="hidden" id="${image.productimageSrc}" name="detailsPicture"
                           value="${image.productimageSrc}"/>
                </li>
            </c:forEach>
            <li class="details_picList_fileUpload">
                <svg class="icon" viewBox="0 0 1024 1024" version="1.1" xmlns="http://www.w3.org/2000/svg" p-id="1528"
                     width="40" height="40">
                    <path d="M0 512C0 229.230208 229.805588 0 512 0 794.769792 0 1024 229.805588 1024 512 1024 794.769792 794.194412 1024 512 1024 229.230208 1024 0 794.194412 0 512Z"
                          p-id="1529" fill="#FF7874"></path>
                    <path d="M753.301333 490.666667l-219.946667 0L533.354667 270.741333c0-11.776-9.557333-21.333333-21.354667-21.333333-11.776 0-21.333333 9.536-21.333333 21.333333L490.666667 490.666667 270.72 490.666667c-11.776 0-21.333333 9.557333-21.333333 21.333333 0 11.797333 9.557333 21.354667 21.333333 21.354667L490.666667 533.354667l0 219.904c0 11.861333 9.536 21.376 21.333333 21.376 11.797333 0 21.354667-9.578667 21.354667-21.333333l0-219.946667 219.946667 0c11.754667 0 21.333333-9.557333 21.333333-21.354667C774.634667 500.224 765.077333 490.666667 753.301333 490.666667z"
                          p-id="1530" fill="#FFFFFF"></path>
                </svg>
                <span>点击上传</span>
                <input type="file" onchange="uploadImage(this)" accept="image/*" class="product_details_image_list">
            </li>
        </ul>
    </div>
    <div class="details_div details_div_last details_property_list">
        <span class="details_title text_info">属性值信息</span>
        <c:forEach items="${product.propertyList}" var="property" varStatus="status">
            <c:choose>
                <c:when test="${status.index % 2 == 0}">
                    <label class="frm_label lbl_property_name text_info"
                           id="lbl_product_property_${property.propertyId}"
                           for="input_product_property_${property.propertyId}">${property.propertyName}</label>
                    <c:choose>
                        <c:when test="${property.propertyValueList != null}">
                            <c:forEach items="${property.propertyValueList}" var="propertyValue">
                                <input class="frm_input" id="input_product_property_${property.propertyId}" type="text"
                                       maxlength="50" value="${propertyValue.propertyvalueValue}"
                                       data-pvid="${propertyValue.propertyvalueId}"
                                       name="propertys[${property.propertyId}]"/>
                            </c:forEach>
                        </c:when>
                        <c:otherwise>
                            <input class="frm_input" id="input_product_property_${property.propertyId}" type="text"
                                   maxlength="50" name="propertys[${property.propertyId}]"/>
                        </c:otherwise>
                    </c:choose>
                </c:when>
                <c:otherwise>
                    <label class="frm_label lbl_property_name text_info"
                           id="lbl_product_property_${property.propertyId}"
                           for="input_product_property_${property.propertyId}">${property.propertyName}</label>
                    <c:choose>
                        <c:when test="${property.propertyValueList != null}">
                            <c:forEach items="${property.propertyValueList}" var="propertyValue">
                                <input class="frm_input" id="input_product_property_${property.propertyId}" type="text"
                                       maxlength="50" value="${propertyValue.propertyvalueValue}"
                                       data-pvid="${propertyValue.propertyvalueId}"
                                       name="propertys[${property.propertyId}]"/>
                            </c:forEach>
                        </c:when>
                        <c:otherwise>
                            <input class="frm_input" id="input_product_property_${property.propertyId}" type="text"
                                   maxlength="50" name="propertys[${property.propertyId}]"/>
                        </c:otherwise>
                    </c:choose>
                    <div class="br"></div>
                </c:otherwise>
            </c:choose>
        </c:forEach>
    </div>

    <div class="details_tools_div">
        <input class="frm_btn" id="btn_product_save" type="submit" value="保存"/>
        <input class="frm_btn frm_clear" id="btn_product_cancel" type="button" value="取消"
               onclick="window.location='/admin/product'"/>
    </div>
</form>

<%-- 模态框 --%>
<div class="modal fade" id="modalDiv" tabindex="-1" role="dialog" aria-labelledby="modalDiv" aria-hidden="true"
     data-backdrop="static">
    <div class="modal-dialog">
        <div class="modal-content">
            <div class="modal-header">
                <h4 class="modal-title" id="myModalLabel">提示</h4>
            </div>
            <div class="modal-body">您确定要删除该产品图片吗？</div>
            <div class="modal-footer">
                <button type="submit" class="btn btn-primary" id="btn-ok">确定</button>
                <button type="button" class="btn btn-default" data-dismiss="modal" id="btn-close">关闭</button>
            </div>
        </div>
        <%-- /.modal-content --%>
    </div>
    <%-- /.modal --%>
</div>
<div class="loader"></div>
</div>
</div>
<script>
    $(function () {
        $("#ul_home_menu li[data-toggle='${currentMenu}']").addClass("menu_li_select")

        if ($("#product_id").val() === '') {
            $("#div_home_title span").text("添加产品")
            document.title = "WolfCode Mall管理后台 - 添加产品"
        } else {
            $("#div_home_title span").text("修改产品")
            document.title = "WolfCode Mall管理后台 - 修改产品"
        }

    })
</script>
</body>
</html>